package com.xtoad.ecms.common.utils;

import com.xtoad.ecms.common.web.exception.BusinessException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 验证码生成工具类
 *
 * @author xtoad
 * @date 2021/02/17
 */
public class CaptchaUtils {

    /**
     * 验证码高度
     */
    private Integer height = 42;
    /**
     * 验证码宽度
     */
    private Integer width = 120;
    /**
     * 干扰线数量
     */
    private Integer lineNumber = 20;
    /**
     * 验证码字符个数
     */
    private Integer charNumber = 4;
    /**
     * 字体大小
     */
    private Integer fontSize = 28;
    /**
     * 验证码字符串
     */
    private StringBuilder captcha;

    /**
     * 验证码字符范围
     * 移除了大小写字母O，移除了小写字母L， 移除了数字0
     */
    private static final char[] CODE_SEQUENCE = {
            'a', 'b', 'c', 'd', 'e', 'f', 'g',
            'h', 'i', 'j', 'k', 'm', 'n',
            'p', 'q', 'r', 's', 't',
            'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G',
            'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z',
            '2', '3', '4', '5', '6', '7', '8', '9'};


    /**
     * 单例对象
     */
    private static volatile CaptchaUtils instance;

    /**
     * 私有构造方法
     */
    private CaptchaUtils() {
    }

    /**
     * 取得对象
     *
     * @return 对象
     */
    public static synchronized CaptchaUtils getInstance() {
        if (instance == null) {
            synchronized (CaptchaUtils.class) {
                if (instance == null) {
                    instance = new CaptchaUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 指定宽高生成验证码
     *
     * @param width      宽度
     * @param height     高度
     * @param charNumber 字符个数
     * @return 验证码图像
     */
    public byte[] generate(Integer width, Integer height, Integer charNumber) {
        this.width = width;
        this.height = height;
        this.charNumber = charNumber;
        return this.generate();
    }

    /**
     * 按默认参数生成验证码图像
     *
     * @return 验证码图像
     */
    public byte[] generate() {
        // 1.创建空白图片
        BufferedImage image = new BufferedImage(
                this.width, this.height, BufferedImage.TYPE_INT_RGB);
        // 2.获取图片画笔
        Graphics graphic = image.getGraphics();
        // 3.设置画笔颜色
        graphic.setColor(Color.LIGHT_GRAY);
        // 4.绘制矩形背景
        graphic.fillRect(0, 0, this.width, this.height);
        // 5.画随机字符
        Random ran = new Random();
        captcha = new StringBuilder();
        for (int i = 0; i < this.charNumber; i++) {
            // 取随机字符索引
            int n = ran.nextInt(CODE_SEQUENCE.length);
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 设置字体大小
            graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, this.fontSize));
            // 画字符
            graphic.drawString(
                    CODE_SEQUENCE[n] + "", i * this.width / this.charNumber, this.height * 2 / 3);
            // 记录字符
            captcha.append(CODE_SEQUENCE[n]);
        }
        // 6.画干扰线
        for (int i = 0; i < this.lineNumber; i++) {
            // 设置随机颜色
            graphic.setColor(getRandomColor());
            // 随机画线
            graphic.drawLine(ran.nextInt(this.width), ran.nextInt(this.height),
                    ran.nextInt(this.width), ran.nextInt(this.height));
        }

        return ImgToByte(image);
    }

    /**
     * 取得验证码字符串
     *
     * @return 验证码
     */
    public String getCaptcha() {
        return this.captcha.toString();
    }

    /**
     * 随机取色
     *
     * @return 颜色
     */
    private Color getRandomColor() {
        Random ran = new Random();
        Color color = new Color(ran.nextInt(256),
                ran.nextInt(256), ran.nextInt(256));
        return color;
    }

    /**
     * BufferedImage 转为 byte数组
     *
     * @param image 图像对象
     * @return 字节数组
     */
    private byte[] ImgToByte(BufferedImage image) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpeg", out);
        } catch (IOException e) {
            throw new BusinessException("000500", "生成验证码出错");
        }

        return out.toByteArray();
    }
}
